package io.gitee.kotle.base

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import io.gitee.kotle.android.utils.StatusData
import io.gitee.kotle.base.library.IUiViewHelper

interface OnStatusDataAttachViewListener<T> {
    fun onRunning(view: IUiViewHelper, data: StatusData<T>) {
        view.showLoading()
    }

    fun onError(view: IUiViewHelper, data: StatusData<T>) {
        view.showError()
    }

    fun onSuccess(view: IUiViewHelper, data: StatusData<T>) {
        view.showContent()
    }

    fun onNull(view: IUiViewHelper) {

    }
}

/**
 * 绑定data
 */
fun <T> LiveData<StatusData<T>>.observerStatusDataAttachView(
    life: LifecycleOwner?,
    helper: IUiViewHelper,
    listener: OnStatusDataAttachViewListener<T>,
): Observer<StatusData<T>> {
    val observer = Observer<StatusData<T>> {
        if (it == null) {
            listener.onNull(helper)
            return@Observer
        }
        when (it.status) {
            StatusData.Running -> {
                listener.onRunning(helper, it)
            }
            StatusData.Error -> {
                listener.onError(helper, it)
            }
            StatusData.Success -> {
                listener.onSuccess(helper, it)
            }
        }
    }
    if (life != null) {
        this.observe(life, observer)
    } else {
        this.observeForever(observer)
    }
    return observer
}

inline fun <T> LiveData<StatusData<T>>.observerStatusDataAttachView(
    life: LifecycleOwner?,
    helper: IUiViewHelper,
    crossinline doSuccess: Function1<T, Unit>,
): Observer<StatusData<T>> {
    return observerStatusDataAttachView(life, helper, object : OnStatusDataAttachViewListener<T> {
        override fun onSuccess(view: IUiViewHelper, data: StatusData<T>) {
            super.onSuccess(view, data)
            val value = data.data
            if (value != null) {
                doSuccess.invoke(value)
            }
        }
    })
}